
"""采购单的改造"""

from odoo import models, api, fields
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError





class PurchaseOrder(models.Model):
    _name = 'purchase.order'
    _inherit = ['purchase.order', 'gsp.business.check']

    @api.model
    def create(self, vals):
        res = super().create(vals)
        res.apply_gsp_manage()
        return res

    @api.multi
    def write(self, vals):
        res = super().write(vals)
        self.apply_gsp_manage()
        return res

    @api.multi
    def button_confirm(self):
        """在原生基础上，记录采购价格信息，并检查是否填写税率"""
        self.check_line_tax()
        for purchase in self:
            self.env['product.template'].update_nd_purchase_price(purchase.order_line)
        return super().button_confirm()

    def check_line_tax(self):
        """检查是否填写税率"""
        no_tax_lines = self.mapped('order_line').filtered(lambda x: not x.taxes_id)
        if no_tax_lines:
            raise UserError(f'有采购明细未填写税率：{no_tax_lines[0].product_id.name}')


class PurchaseOrderLine(models.Model):
    _inherit = 'purchase.order.line'

    product_id = fields.Many2one('product.product', domain=[('purchase_ok', '=', True), ('can_use', '=', True)])

    nd_producer_id = fields.Many2one('gsp.producer', string="生产厂家", store=True, related="product_id.producer_id")
    # gift = fields.Boolean('赠品')
    nd_size = fields.Char('产品规格', store=True,related="product_id.nd_size")
    update_product_price = fields.Boolean('已更新产品价格', help="标记此明细是否已更新产品历史价格信息，防止重复")
    nd_qty = fields.Float('可用数量', compute="_compute_nd_qty", store=True)

    @api.multi
    def nd_check_history_price(self):
        """弹出对于产品的历史价格"""
        self.ensure_one()
        if self.product_id:
            return self.env['purchase.order']._nd_check_price(self.product_id)

    @api.depends('product_id')
    def _compute_nd_qty(self):
        for line in self:
            if line.product_id:
                line.nd_qty = line.order_id._get_qty_available_for_product(line.product_id)




